<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/12 0012
 * Time: 16:00
 */

namespace backend\controllers;


use backend\components\BaseComponentController;
use common\components\ActionsComponents\ListViewAction;
use common\models\Admin\Admin;
use common\models\AgentInfo\AgentInfo;
use common\models\AgentPlugs\AgentPlugs;
use common\models\Plug\Plug;
use common\models\RegionManagerInfo\RegionManagerInfo;
use yii\helpers\Url;

class AgentController extends BaseComponentController
{
    public function beforeAction($action)
    {
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    public function actions()
    {
        return [
            "index" => [
                "class" => ListViewAction::class,
                "model" => Admin::class,
                "with" => ["agentInfo.manager.regionManagerInfo", "agentInfo.parentAgentInfo"],
                "condition" => function(){
                    if ( Admin::isRegionManagerCurrent() ) {
                        return [
                            "id" => Admin::getAgentIdsByCurrentManager()
                        ];
                    } elseif ( Admin::isAgentCurrent() ) {
                        return [
                            "id" => Admin::getAgentIdsByCurrentAgent()
                        ];
                    }
                    return [
                        "type" => Admin::TYPE_AGENT
                    ];
                }
            ],
            "plugs-list" => [
                "class" => ListViewAction::class,
                "model" => Admin::class,
                "with" => "agentInfo.manager.regionManagerInfo",
                "params" => [
                    "plugs_button" => 1
                ],
                "condition" => function() {
                    if ( Admin::isAgentCurrent() ) {
                        return [
                            "id" => -1
                        ];
                    }
                    if (Admin::isRegionManagerCurrent()) {
                        return [
                            "id" => Admin::getAgentIdsByCurrentManager()
                        ];
                    }
                    return [
                        "type" => Admin::TYPE_AGENT
                    ];
                }
            ],
        ]; // TODO: Change the autogenerated stub
    }

    public function actionItem()
    {
        if ( ($id = $this->get("id")) ) {
            $user = Admin::findOne([
                "id" => $id,
                "type" => Admin::TYPE_AGENT
            ]);
            if ( !$user ) {
                return $this->redirect(Url::to(["index"]));
            }
            if ( Admin::isRegionManagerCurrent() ) {
                if ( $user->agentInfo["parent_manager"] != $this->uid ) {
                    return $this->redirect(Url::to(["index"]));
                }
            }
        } else {
            $user = [];
        }
        //获取上级代理
        $parentAgent = AgentInfo::find()->where([
            "parent_agent" => 0
        ])->select(["uid", "name"])->with([
            "accountInfo" => function($query) {
                $query->select("username");
            }
        ]);
        if ( $this->isManager() ) {
            $parentAgent->andWhere([
                "parent_manager" => $this->uid
            ]);
        } elseif ( $this->isAgent() ) {
            $parentAgent->andWhere([
                "uid" => $this->uid
            ]);
        }
        $parentAgent = $user ? $parentAgent->andWhere("uid<>" . $user->id)->all() : $parentAgent->all();

        //获取上级代理
        $parentManager = RegionManagerInfo::find()->select(["uid", "name"])->with([
            "accountInfo" => function($query) {
                $query->select("username");
            }
        ]);
        if ( Admin::isRegionManagerCurrent() ) {
            $parentManager->andWhere([
                "uid" => $this->uid
            ]);
        }
        $parentManager = $parentManager->all();
        return $this->render("item", [
            "ret" => $user,
            "parentAgent" => $parentAgent,
            "parentManager" => $parentManager,

        ]);
    }

    public function actionUpdateStatus()
    {
        $user = Admin::findOne([
            "id" => $this->requestAll("id"),
            "type" => Admin::TYPE_AGENT
        ]);
        if ( !$user ) {
            return $this->jsonResponse(self::RESPONSE_FAILURE, "未知的用户");
        }
        if ( Admin::isRegionManagerCurrent() &&  $user->agentInfo["parent_manager"] != $this->uid ) {
            return $this->jsonResponse(self::RESPONSE_FAILURE, "未知的用户");
        }

        return $user->changeStatus($this->requestAll("status")) ? $this->jsonResponse(self::RESPONSE_SUCCESS) : $this->jsonResponse(self::RESPONSE_FAILURE);
    }

    public function actionSet()
    {
        $params = $this->post();
        if ( $this->isAgent() ) {
            if ( !$this->isAgentTop() ) {
                return $this->jsonResponse(self::RESPONSE_FAILURE, "不是顶级代理");
            }
            $params["parent_agent"] = $this->uid;
        }
        if ( Admin::setUserAccount($params, Admin::TYPE_AGENT, @$params["id"]) ) {
            return $this->jsonResponse(self::RESPONSE_SUCCESS);
        }
        return $this->jsonResponse(self::RESPONSE_FAILURE, Admin::error());
    }

    public function actionPlugs()
    {
        $agentId = $this->get("uid");
        if ( !$agentId ) {
            return $this->redirect(Url::to(["index"]));
        } else {
            $agent = Admin::findOne([
                "id" => $agentId,
                "type" => Admin::TYPE_AGENT
            ]);
            if ( !$agent ) {
                return $this->redirect(Url::to(["index"]));
            }
            if ( Admin::isRegionManagerCurrent() &&  $agent->agentInfo["parent_manager"] != $this->uid ) {
                return $this->redirect(Url::to(["index"]));
            }
        }
        //获取所有可用的插件
        $plugs = Plug::find()->where([
            "status" => Plug::STATUS_YES
        ])->asArray()->all();

        $agentPlugs = AgentPlugs::find()->select(["plug_id"])->where([
            "agent_uid" => $agentId
        ])->asArray()->all();
        $agentPlugs = array_column($agentPlugs, "plug_id");
        $this->layout = self::LAYER_CONTENT;
        return $this->render("plugs", [
            "plugs" => $plugs,
            "agent_id" => $agentId,
            "agentPlugs"=> $agentPlugs
        ]);
    }

    public function actionSetPlugs()
    {
        $agentUid = $this->requestAll("agent_uid");
        $agent = Admin::findOne([
            "id" => $agentUid,
            "type" => Admin::TYPE_AGENT
        ]);
        if ( !$agent ) {
            return $this->jsonResponse(self::RESPONSE_FAILURE, "无效的代理商");
        }
        if ( Admin::isRegionManagerCurrent() &&  $agent->agentInfo["parent_manager"] != $this->uid ) {
            return $this->jsonResponse(self::RESPONSE_FAILURE, "无效的代理商");
        }
        $agentPlugs = new AgentPlugs();
        $ret = $agentPlugs->setLinkRows("agent_uid", $agentUid, "plug_id", (array)$this->post("plugs_id"));
        if ( $ret ) {
            if ( !AgentPlugs::generateJsonFile($agentUid) ) {
                return $this->jsonResponse(self::RESPONSE_SUCCESS, "数据保存成功，但json文件生成失败");
            }
            return $this->jsonResponse(self::RESPONSE_SUCCESS);
        }
        return $this->jsonResponse(self::RESPONSE_FAILURE);
    }
}